//
//  mm_jobItemGroupViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-31.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_jobItemGroupViewController.h"
#import "mm_userDefinedCellForRepairItem.h"
#import "mm_userDefinedCellForPart.h"
#import "MyAFNetWorkManager.h"
#import "MJRefresh.h"

@interface mm_jobItemGroupViewController ()

/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;
@property (strong, nonatomic) IBOutlet UIButton *carTypeBtn;
@property (weak, nonatomic) IBOutlet UIButton *chargeDiffBtn;
@property (weak, nonatomic) IBOutlet UITextField *repairGroupCodeTxt;

//存储维修项目列表和零件列表数据
@property(nonatomic,strong)NSMutableArray *arrRepairItemList;
@property(nonatomic,strong)NSMutableArray *arrPartList;

/** 维修车型组数据列表 */
@property(nonatomic,strong)NSMutableArray *arrDisDataForCarType;
@property(nonatomic,strong)NSMutableDictionary *carTypeDic;

@property(nonatomic,assign)int from;
@property(nonatomic,assign)int to;

/** 维修分类 */
@property(nonatomic,strong)NSMutableDictionary *repairTypeCodeDic;

@end

@implementation mm_jobItemGroupViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //设置MJRefresh
    __weak typeof(self.repairItemTableViewDis) weekRepairTable = self.repairItemTableViewDis;
    self.repairItemTableViewDis.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self queryBtnClicked];
        [weekRepairTable.mj_header endRefreshing];
    }];
    
    __weak typeof(self.partTableViewDis) weekPartTable = self.partTableViewDis;
    self.partTableViewDis.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self queryBtnClicked];
        [weekPartTable.mj_header endRefreshing];
    }];
    
    weekRepairTable.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self queryNextPageData];
        [weekRepairTable.mj_footer endRefreshing];
    }];
    
    weekPartTable.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self queryNextPageData];
        [weekPartTable.mj_footer endRefreshing];
    }];
}



#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger nRowSum = 0;
    
    if (tableView == self.repairItemTableViewDis)
    {
        nRowSum = [_arrRepairItemList count];
    }
    else if (tableView == self.partTableViewDis)
    {
        nRowSum = [_arrPartList count];
    }
    
    return 3+nRowSum;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell && tableView == self.repairItemTableViewDis)
    {
        cell = (mm_userDefinedCellForRepairItem *)[[mm_userDefinedCellForRepairItem alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    else if (nil == cell && tableView == self.partTableViewDis)
    {
        cell = (mm_userDefinedCellForPart *)[[mm_userDefinedCellForPart alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    NSInteger row = [indexPath row];
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            break;
            
        default:
            break;
    }
    
    //给 cell 上设置数据
    NSArray *arrDisTmp = nil;
    NSArray *arrAllKeysTmp =  nil;
    NSMutableDictionary *dicAllLblsOnCellTmp = nil;
    
    //(1)设置要显示的列表（数组）
    if (tableView == self.repairItemTableViewDis)
    {
        arrDisTmp = _arrRepairItemList;
        arrAllKeysTmp = ((mm_userDefinedCellForRepairItem *)cell).arrAllKeys;
        dicAllLblsOnCellTmp = ((mm_userDefinedCellForRepairItem *)cell).dicAllLblsOnCell;
    }
    else if (tableView == self.partTableViewDis)
    {
        arrDisTmp = _arrPartList;
        arrAllKeysTmp = ((mm_userDefinedCellForPart *)cell).arrAllKeys;
        dicAllLblsOnCellTmp = ((mm_userDefinedCellForPart *)cell).dicAllLblsOnCell;
    }
    
    
    //(2)给自定义 cell 赋值
    if (row<[arrDisTmp count])
    {
        for (int i = 0; i<[arrAllKeysTmp count]; i++)
        {
            NSString *strKey = [arrAllKeysTmp objectAtIndex:i];
            NSDictionary *dic = arrDisTmp[row];
            id text = dic[strKey];
            if ([text isKindOfClass:[NSNumber class]]) {
                text = [text stringValue];
            }else if ([strKey isEqualToString:@"REPAIR_TYPE_CODE"]){//维修分类
                text = self.repairTypeCodeDic[text];
            }else{
                text = dic[strKey];
            }
            
            ((UILabel *)[dicAllLblsOnCellTmp objectForKey:strKey]).text = text;
        }
    }
    else
    {
        for (int i = 0; i<[arrAllKeysTmp count]; i++)
        {
            NSString *strKey = [arrAllKeysTmp objectAtIndex:i];
            ((UILabel *)[dicAllLblsOnCellTmp objectForKey:strKey]).text = @"";
        }
    }
    
    //(3)设置所有的 cell 不可选
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


- (IBAction)backBtnPressed:(UIButton *)sender
{
    //返回上一级界面
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)carTypePressed:(UIButton *)sender
{
    //创建下拉菜单控件
    [self createThePopViewControl:sender];
    _contentCon.list = self.arrDisDataForCarType;
    [_contentCon.myTableView reloadData];
}


- (IBAction)chargeDiffBtnPressed:(UIButton *)sender
{
    //创建下拉菜单
    [self createThePopViewControl:sender];
    
    //刷新下拉菜单数据
    _contentCon.list = self.chargeDiffKeys;
    [_contentCon.myTableView reloadData];
}

- (IBAction)addOkBtnPressed:(UIButton *)sender
{
    NSString *msg = [self validInput];
    
    if (msg)
    {
        //提示选择用户陈述
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];        
        return;
    }
    
    //添加数据
    [self addOneIndicationToIndicationList];
    
    //调用代理方法
    if ([self.delegate respondsToSelector:@selector(repairAndPartListDataChanged)]) {
        [self.delegate repairAndPartListDataChanged];
    }
    [self backBtnPressed:nil];
}

-(NSString *)validInput{
    NSString *msg = nil;
    if (!_arrRepairItemList.count||!_arrPartList.count){
        msg = @"没有添加的数据";
    }else if (self.chargeDiffBtn.titleLabel.text.length<=0){
        msg = @"请选择收费区分";
    }
    return msg;
}

- (IBAction)continuously:(UIButton *)sender
{
        
    //(2)调用添加作业指示的方法
    [self addOneIndicationToIndicationList];
    
//    //提示“是否要继续进行成组录入”
//    _alertViewToContinuouslyAddJobItemGroup = [[UIAlertView alloc] initWithTitle:nil message:@"是否要继续进行成组录入" delegate:self cancelButtonTitle:@"继续" otherButtonTitles:@"退出", nil];
//    [_alertViewToContinuouslyAddJobItemGroup show];
    
    [self initJobItemGroupAtFirst];
    
    //给上一级VC发一个消息，调用“成组录入”按钮的回调方法
//    [[NSNotificationCenter defaultCenter] postNotificationName:MM_TO_INVOKE_JOB_ITEM_GROUP_BTN_MSG_ object:nil];
}

//创建下拉菜单
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!_contentCon)
    {
        _contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    _contentCon.delegate = self;
    _contentCon.btnSender=sender;
    
    _popCon = [[UIPopoverController alloc] initWithContentViewController:_contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [_popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [_popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [_popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

#pragma mark - 下拉框选中行回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *key = nil;
    if (btn == self.carTypeBtn)
    {
        key = self.arrDisDataForCarType[row];
    }
    else if (btn == self.chargeDiffBtn)
    {
        key = self.chargeDiffKeys[row];
    }
    
    [btn setTitle:key forState:UIControlStateNormal];
    //清空下拉菜单的数据，并dismiss掉下拉菜单
    _contentCon.list = nil;
    [_popCon dismissPopoverAnimated:YES];
    _popCon = nil;
}

//进入界面时的初始化操作
-(void)initJobItemGroupAtFirst
{
    
    //设置数据初值
    _arrRepairItemList = nil;
    _arrPartList = nil;
    
    //设置控件初始状态
    [self.carTypeBtn setTitle:@"" forState:UIControlStateNormal];
    [self.chargeDiffBtn setTitle:@"" forState:UIControlStateNormal];
    self.jobItemGroupNameTxt.text = @"";
}

//添加数据到列表中
-(void)addOneIndicationToIndicationList
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *chargeDiffVal = self.chargeDiff[self.chargeDiffBtn.titleLabel.text];
    if (!chargeDiffVal) {
        chargeDiffVal = @"";
    }
    //维修项目列表
    for (int i = 0; i<[_arrRepairItemList count]; i++)
    {
        NSMutableDictionary *dicRepairItem = _arrRepairItemList[i];
        [dicRepairItem setObject:@"" forKey:@"ITEM_ID"];
        [dicRepairItem setObject:@"A" forKey:@"STATUS"];
        [dicRepairItem setObject:@(self.repairDiscount) forKey:@"DISCOUNT"];
        [dicRepairItem setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    }
    if (modelIns.repairProjects.count) {
        NSRange rangge = NSMakeRange(0,_arrRepairItemList.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:rangge];
        [modelIns.repairProjects insertObjects:_arrRepairItemList atIndexes:indexSet];
    }else{
        modelIns.repairProjects = _arrRepairItemList;
    }
    
    //零件列表
    for (int i = 0; i<[_arrPartList count]; i++)
    {
        NSMutableDictionary *dicPart = _arrPartList[i];
        [dicPart setObject:@"" forKey:@"ITEM_ID"];
        [dicPart setObject:@"A" forKey:@"STATUS"];
        [dicPart setObject:@(self.partDiscount) forKey:@"DISCOUNT"];
        [dicPart setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    }
    if (modelIns.partList.count) {
        NSRange rangge = NSMakeRange(0,_arrPartList.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:rangge];
        [modelIns.partList insertObjects:_arrPartList atIndexes:indexSet];
    }else{
        modelIns.partList = _arrPartList;
    }
}

//根据列表的编号取服务类型的ID
-(NSString *)getServiceTypeIdByRowSel:(NSInteger)rowSel
{
    if (-1 == rowSel)
    {
        
        return @"";
    }
    return [[_arrOriginalDataForServiceType objectAtIndex:rowSel] objectForKey:@"serviceTypeId"];
}

//根据列表的编号取修理类型的ID
-(NSString *)getRepairTypeIdByRowSel:(NSInteger)rowSel
{
    if (-1 == rowSel)
    {
        
        return @"";
    }
    return [[_arrOriginalDataForRepairType objectAtIndex:rowSel] objectForKey:@"repairTypeId"];
}

#pragma mark -懒加载
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_chargeDiffKeys addObject:name];
            [_chargeDiff setObject:val forKey:name];
        }
    }
    return _chargeDiffKeys;
}

/** 维修车型组 */
-(NSMutableArray *)arrDisDataForCarType{
    if (_arrDisDataForCarType == nil) {
        _arrDisDataForCarType= [NSMutableArray array];
        _carTypeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_MODEL_LABOUR"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if (name&&val) {
                [_arrDisDataForCarType addObject:name];
                [_carTypeDic setObject:val forKey:name];
            }
        }
    }
    return _arrDisDataForCarType;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

#pragma mark - 查询点击
- (IBAction)queryBtnClicked {
    _arrRepairItemList = nil;
    _arrPartList = nil;
    self.from = 0;
    self.to = 10;
    [self queryData];
}

-(void)queryData{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    NSString *group = self.carTypeBtn.titleLabel.text;
    NSString *groupCode = self.repairGroupCodeTxt.text;
    NSString *groupName = self.jobItemGroupNameTxt.text;
    if (group.length>0) {
        [param setObject:self.carTypeDic[group] forKey:@"MODEL_LABOUR_CODE"];
    }
    if (groupCode.length>0) {
        [param setObject:groupCode forKey:@"PACKAGE_CODE"];
    }
    if (groupName.length>0) {
        [param setObject:[groupName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PACKAGE_NAME"];
    }
    [param setObject:@(_from) forKey:@"LABOUR_FROM"];
    [param setObject:@(_to) forKey:@"LABOUR_TO"];
    [param setObject:@(_from) forKey:@"PART_FROM"];
    [param setObject:@(_to) forKey:@"PART_TO"];
    [SVProgressHUD showWithStatus:@"请等待...."];
    
    [MyAFNetWorkManager postWithParam:param andAction:@"SYNC_GET_PACKAGE_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        if (!error) {
            NSMutableArray *repairList = obj[@"TM_PACKAGE_LABOUR"];
            NSMutableArray *partList = obj[@"TM_PACKAGE_PART"];
            if (self.arrRepairItemList) {
                NSRange range = {0,repairList.count};
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
                [self.arrRepairItemList insertObjects:repairList atIndexes:indexSet];
                
                NSRange partRange = {0,partList.count};
                indexSet = [NSIndexSet indexSetWithIndexesInRange:partRange];
                [self.arrPartList insertObjects:partList atIndexes:indexSet];
            }else{
                self.arrRepairItemList = repairList;
                self.arrPartList = partList;
            }
            
            //刷新表单
            [self.repairItemTableViewDis reloadData];
            [self.partTableViewDis reloadData];
        }else{
            NSLog(@"%@",error);
        }
        
    }];
}

-(void)queryNextPageData
{
    _from += 10;
    _to += 10;
    [self queryData];
}

-(NSMutableDictionary *)repairTypeCodeDic{
    if (_repairTypeCodeDic == nil) {
        _repairTypeCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeCodeDic setObject:name forKey:val];
        }
    }
    return _repairTypeCodeDic;
}


@end
